"""
分类管理页面

管理素材分类的页面 - 美化版
支持分类的增删改查、层级管理、批量操作等功能
"""

import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
from pathlib import Path
import sys
import json
from typing import Dict, List, Optional

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

from src.gui.main_app import BasePage
from src.gui.design_system import (DesignSystem, create_card_frame,
                                  create_primary_button, create_secondary_button,
                                  create_success_button, create_danger_button)


class CategoryManagementPage(BasePage):
    """分类管理页面"""

    def __init__(self, parent, app):
        super().__init__(parent, app)
        self.categories = []  # 分类数据
        self.selected_category = None  # 当前选中的分类
        self.category_stats = {}  # 分类统计信息

    def create_page(self):
        """创建页面内容"""
        self.frame = ttk.Frame(self.parent)

        # 页面标题
        self.create_header()

        # 主要内容区域
        self.create_main_content()

        # 加载示例数据
        self.load_sample_data()

    def create_header(self):
        """创建页面标题"""
        header_frame = ttk.Frame(self.frame)
        header_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))

        # 标题区域
        title_container = ttk.Frame(header_frame)
        title_container.pack(side="left", fill="x", expand=True)

        title_label = ttk.Label(
            title_container,
            text="🏷️ 分类管理",
            style='Title.TLabel'
        )
        title_label.pack(side="left")

        # 副标题
        subtitle_label = ttk.Label(
            title_container,
            text="管理素材分类和标签体系",
            style='Muted.TLabel'
        )
        subtitle_label.pack(side="left", padx=(DesignSystem.SPACING['md'], 0))

        # 操作按钮区域
        action_frame = ttk.Frame(header_frame)
        action_frame.pack(side="right")

        # 返回按钮
        back_btn = create_secondary_button(
            action_frame,
            text="← 返回列表",
            command=lambda: self.app.show_page("material_list")
        )
        back_btn.pack(side="right")

    def create_main_content(self):
        """创建主要内容区域"""
        # 主内容容器
        main_container = ttk.Frame(self.frame)
        main_container.pack(fill="both", expand=True)

        # 左侧：分类树和操作
        self.create_left_panel(main_container)

        # 右侧：分类详情和统计
        self.create_right_panel(main_container)

    def create_left_panel(self, parent):
        """创建左侧面板"""
        left_frame = ttk.Frame(parent)
        left_frame.pack(side="left", fill="both", expand=True,
                       padx=(0, DesignSystem.SPACING['lg']))

        # 工具栏
        self.create_toolbar(left_frame)

        # 分类树
        self.create_category_tree(left_frame)

    def create_right_panel(self, parent):
        """创建右侧面板"""
        right_frame = ttk.Frame(parent, width=350)
        right_frame.pack(side="right", fill="y")
        right_frame.pack_propagate(False)

        # 分类详情
        self.create_category_details(right_frame)

        # 分类统计
        self.create_category_statistics(right_frame)

    def create_toolbar(self, parent):
        """创建工具栏"""
        toolbar_frame = create_card_frame(parent, "分类操作")
        toolbar_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))

        # 第一行：搜索和筛选
        search_row = ttk.Frame(toolbar_frame)
        search_row.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))

        # 搜索框
        search_container = ttk.Frame(search_row)
        search_container.pack(side="left", fill="x", expand=True)

        ttk.Label(search_container, text="🔍 搜索分类:", style='Heading.TLabel').pack(side="left")

        self.search_var = tk.StringVar()
        search_entry = ttk.Entry(search_container, textvariable=self.search_var, width=25)
        search_entry.pack(side="left", padx=(DesignSystem.SPACING['sm'], DesignSystem.SPACING['lg']))
        search_entry.bind("<KeyRelease>", self.on_search_changed)

        # 展开/折叠按钮
        expand_container = ttk.Frame(search_row)
        expand_container.pack(side="right")

        expand_btn = create_secondary_button(
            expand_container,
            text="📂 全部展开",
            command=self.expand_all_categories
        )
        expand_btn.pack(side="right", padx=(DesignSystem.SPACING['sm'], 0))

        collapse_btn = create_secondary_button(
            expand_container,
            text="📁 全部折叠",
            command=self.collapse_all_categories
        )
        collapse_btn.pack(side="right")

        # 第二行：操作按钮
        action_row = ttk.Frame(toolbar_frame)
        action_row.pack(fill="x")

        # 左侧按钮组
        left_actions = ttk.Frame(action_row)
        left_actions.pack(side="left")

        add_btn = create_primary_button(
            left_actions,
            text="➕ 新建分类",
            command=self.add_category
        )
        add_btn.pack(side="left", padx=(0, DesignSystem.SPACING['sm']))

        add_sub_btn = create_secondary_button(
            left_actions,
            text="📁 新建子分类",
            command=self.add_subcategory
        )
        add_sub_btn.pack(side="left", padx=(0, DesignSystem.SPACING['sm']))

        # 右侧按钮组
        right_actions = ttk.Frame(action_row)
        right_actions.pack(side="right")

        import_btn = create_secondary_button(
            right_actions,
            text="📥 导入分类",
            command=self.import_categories
        )
        import_btn.pack(side="right", padx=(DesignSystem.SPACING['sm'], 0))

        export_btn = create_secondary_button(
            right_actions,
            text="📤 导出分类",
            command=self.export_categories
        )
        export_btn.pack(side="right", padx=(DesignSystem.SPACING['sm'], 0))

        delete_btn = create_danger_button(
            right_actions,
            text="🗑️ 删除分类",
            command=self.delete_category
        )
        delete_btn.pack(side="right")

    def create_category_tree(self, parent):
        """创建分类树"""
        tree_frame = create_card_frame(parent, "分类结构")
        tree_frame.pack(fill="both", expand=True)

        # 树形控件容器
        tree_container = ttk.Frame(tree_frame)
        tree_container.pack(fill="both", expand=True)

        # 创建Treeview
        columns = ('count', 'type', 'status')
        self.category_tree = ttk.Treeview(tree_container, columns=columns, show='tree headings', height=15)

        # 设置列标题和宽度
        self.category_tree.heading('#0', text='📂 分类名称')
        self.category_tree.heading('count', text='📊 素材数量')
        self.category_tree.heading('type', text='🏷️ 类型')
        self.category_tree.heading('status', text='🔄 状态')

        # 设置列宽
        self.category_tree.column('#0', width=200, anchor='w')
        self.category_tree.column('count', width=80, anchor='center')
        self.category_tree.column('type', width=80, anchor='center')
        self.category_tree.column('status', width=80, anchor='center')

        # 滚动条
        v_scrollbar = ttk.Scrollbar(tree_container, orient="vertical", command=self.category_tree.yview)
        h_scrollbar = ttk.Scrollbar(tree_container, orient="horizontal", command=self.category_tree.xview)
        self.category_tree.configure(yscrollcommand=v_scrollbar.set, xscrollcommand=h_scrollbar.set)

        # 布局
        self.category_tree.grid(row=0, column=0, sticky="nsew")
        v_scrollbar.grid(row=0, column=1, sticky="ns")
        h_scrollbar.grid(row=1, column=0, sticky="ew")

        tree_container.grid_rowconfigure(0, weight=1)
        tree_container.grid_columnconfigure(0, weight=1)

        # 绑定事件
        self.category_tree.bind("<<TreeviewSelect>>", self.on_category_selected)
        self.category_tree.bind("<Double-1>", self.on_category_double_click)
        self.category_tree.bind("<Button-3>", self.show_category_context_menu)

        # 添加空状态提示
        self.create_empty_category_state(tree_frame)

    def create_empty_category_state(self, parent):
        """创建空状态提示"""
        self.empty_category_frame = ttk.Frame(parent)

        empty_icon = ttk.Label(
            self.empty_category_frame,
            text="🏷️",
            font=(DesignSystem.FONTS['family_primary'], 48),
            foreground=DesignSystem.COLORS['text_muted']
        )
        empty_icon.pack(pady=(50, DesignSystem.SPACING['lg']))

        empty_title = ttk.Label(
            self.empty_category_frame,
            text="暂无分类",
            style='Heading.TLabel'
        )
        empty_title.pack()

        empty_desc = ttk.Label(
            self.empty_category_frame,
            text="点击「新建分类」按钮创建您的第一个分类",
            style='Muted.TLabel'
        )
        empty_desc.pack(pady=(DesignSystem.SPACING['sm'], DesignSystem.SPACING['xl']))

        add_first_btn = create_primary_button(
            self.empty_category_frame,
            text="➕ 创建第一个分类",
            command=self.add_category
        )
        add_first_btn.pack()

    def create_category_details(self, parent):
        """创建分类详情面板"""
        details_frame = create_card_frame(parent, "分类详情")
        details_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))

        # 分类信息显示
        self.details_container = ttk.Frame(details_frame)
        self.details_container.pack(fill="x")

        # 默认提示
        self.create_default_details_view()

        # 编辑表单（初始隐藏）
        self.create_edit_form(details_frame)

    def create_default_details_view(self):
        """创建默认详情视图"""
        self.default_details_frame = ttk.Frame(self.details_container)
        self.default_details_frame.pack(fill="x")

        # 提示图标和文字
        hint_icon = ttk.Label(
            self.default_details_frame,
            text="👆",
            font=(DesignSystem.FONTS['family_primary'], 32),
            foreground=DesignSystem.COLORS['text_muted']
        )
        hint_icon.pack(pady=(DesignSystem.SPACING['xl'], DesignSystem.SPACING['md']))

        hint_text = ttk.Label(
            self.default_details_frame,
            text="选择左侧分类查看详细信息",
            style='Muted.TLabel'
        )
        hint_text.pack()

    def create_edit_form(self, parent):
        """创建编辑表单"""
        self.edit_frame = ttk.Frame(parent)
        # 初始隐藏

        # 分类名称
        name_row = ttk.Frame(self.edit_frame)
        name_row.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))

        ttk.Label(name_row, text="分类名称:", style='Heading.TLabel').pack(anchor="w")
        self.category_name_var = tk.StringVar()
        name_entry = ttk.Entry(name_row, textvariable=self.category_name_var, width=30)
        name_entry.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))

        # 分类描述
        desc_row = ttk.Frame(self.edit_frame)
        desc_row.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))

        ttk.Label(desc_row, text="分类描述:", style='Heading.TLabel').pack(anchor="w")
        self.category_desc_var = tk.StringVar()
        desc_entry = ttk.Entry(desc_row, textvariable=self.category_desc_var, width=30)
        desc_entry.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))

        # 分类颜色
        color_row = ttk.Frame(self.edit_frame)
        color_row.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))

        ttk.Label(color_row, text="标签颜色:", style='Heading.TLabel').pack(anchor="w")
        self.category_color_var = tk.StringVar(value="蓝色")
        color_combo = ttk.Combobox(
            color_row,
            textvariable=self.category_color_var,
            values=["🔵 蓝色", "🟢 绿色", "🟡 黄色", "🔴 红色", "🟣 紫色", "🟠 橙色"],
            state="readonly",
            width=27
        )
        color_combo.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))

        # 分类状态
        status_row = ttk.Frame(self.edit_frame)
        status_row.pack(fill="x", pady=(0, DesignSystem.SPACING['lg']))

        ttk.Label(status_row, text="分类状态:", style='Heading.TLabel').pack(anchor="w")
        self.category_status_var = tk.StringVar(value="启用")
        status_combo = ttk.Combobox(
            status_row,
            textvariable=self.category_status_var,
            values=["✅ 启用", "⏸️ 禁用", "🔒 锁定"],
            state="readonly",
            width=27
        )
        status_combo.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))

        # 操作按钮
        button_row = ttk.Frame(self.edit_frame)
        button_row.pack(fill="x")

        save_btn = create_success_button(
            button_row,
            text="💾 保存",
            command=self.save_category
        )
        save_btn.pack(side="left", padx=(0, DesignSystem.SPACING['sm']))

        cancel_btn = create_secondary_button(
            button_row,
            text="❌ 取消",
            command=self.cancel_edit
        )
        cancel_btn.pack(side="left")

    def create_category_statistics(self, parent):
        """创建分类统计面板"""
        stats_frame = create_card_frame(parent, "分类统计")
        stats_frame.pack(fill="both", expand=True)

        # 统计卡片容器
        stats_container = ttk.Frame(stats_frame)
        stats_container.pack(fill="both", expand=True, pady=DesignSystem.SPACING['md'])

        # 总体统计
        self.create_overall_stats(stats_container)

        # 分类分布图
        self.create_category_distribution(stats_container)

        # 最近活动
        self.create_recent_activity(stats_container)

    def create_overall_stats(self, parent):
        """创建总体统计"""
        overall_frame = ttk.LabelFrame(parent, text="📊 总体统计", padding=DesignSystem.SPACING['md'])
        overall_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))

        # 统计项目
        stats_data = [
            ("总分类数", "12", "🏷️"),
            ("活跃分类", "10", "✅"),
            ("素材总数", "1,234", "📁"),
            ("未分类", "23", "❓")
        ]

        for i, (label, value, icon) in enumerate(stats_data):
            stat_frame = ttk.Frame(overall_frame)
            stat_frame.pack(fill="x", pady=DesignSystem.SPACING['xs'])

            # 图标
            icon_label = ttk.Label(stat_frame, text=icon, font=(DesignSystem.FONTS['family_primary'], 16))
            icon_label.pack(side="left")

            # 标签
            label_text = ttk.Label(stat_frame, text=label, style='Muted.TLabel')
            label_text.pack(side="left", padx=(DesignSystem.SPACING['sm'], 0))

            # 数值
            value_label = ttk.Label(stat_frame, text=value, style='Heading.TLabel')
            value_label.pack(side="right")

    def create_category_distribution(self, parent):
        """创建分类分布"""
        dist_frame = ttk.LabelFrame(parent, text="📈 分类分布", padding=DesignSystem.SPACING['md'])
        dist_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))

        # 分布数据
        distribution_data = [
            ("AI素材", 45, "🤖"),
            ("产品展示", 30, "📦"),
            ("模特试穿", 15, "👗"),
            ("产品使用", 10, "🎯")
        ]

        for category, percentage, icon in distribution_data:
            dist_item = ttk.Frame(dist_frame)
            dist_item.pack(fill="x", pady=DesignSystem.SPACING['xs'])

            # 图标和名称
            info_frame = ttk.Frame(dist_item)
            info_frame.pack(side="left")

            ttk.Label(info_frame, text=icon, font=(DesignSystem.FONTS['family_primary'], 14)).pack(side="left")
            ttk.Label(info_frame, text=category, style='Body.TLabel').pack(side="left", padx=(DesignSystem.SPACING['xs'], 0))

            # 百分比
            ttk.Label(dist_item, text=f"{percentage}%", style='Heading.TLabel').pack(side="right")

            # 进度条
            progress_frame = ttk.Frame(dist_item)
            progress_frame.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))

            progress = ttk.Progressbar(progress_frame, length=200, mode='determinate')
            progress.pack(fill="x")
            progress['value'] = percentage

    def create_recent_activity(self, parent):
        """创建最近活动"""
        activity_frame = ttk.LabelFrame(parent, text="🕒 最近活动", padding=DesignSystem.SPACING['md'])
        activity_frame.pack(fill="both", expand=True)

        # 活动列表
        activities = [
            ("新建分类「夏季新品」", "2分钟前", "➕"),
            ("编辑分类「AI素材」", "5分钟前", "✏️"),
            ("删除分类「测试分类」", "10分钟前", "🗑️"),
            ("导入分类数据", "1小时前", "📥")
        ]

        for activity, time, icon in activities:
            activity_item = ttk.Frame(activity_frame)
            activity_item.pack(fill="x", pady=DesignSystem.SPACING['xs'])

            # 图标
            ttk.Label(activity_item, text=icon, font=(DesignSystem.FONTS['family_primary'], 12)).pack(side="left")

            # 活动描述
            desc_frame = ttk.Frame(activity_item)
            desc_frame.pack(side="left", fill="x", expand=True, padx=(DesignSystem.SPACING['sm'], 0))

            ttk.Label(desc_frame, text=activity, style='Body.TLabel').pack(anchor="w")
            ttk.Label(desc_frame, text=time, style='Muted.TLabel').pack(anchor="w")

    def load_sample_data(self):
        """加载示例数据"""
        # 示例分类数据
        sample_categories = [
            {
                'id': '1',
                'name': 'AI素材',
                'description': '人工智能生成的素材内容',
                'color': '🔵 蓝色',
                'status': '✅ 启用',
                'count': 456,
                'type': '主分类',
                'children': [
                    {'id': '1-1', 'name': 'AI图片', 'count': 234, 'type': '子分类'},
                    {'id': '1-2', 'name': 'AI视频', 'count': 122, 'type': '子分类'},
                    {'id': '1-3', 'name': 'AI音频', 'count': 100, 'type': '子分类'}
                ]
            },
            {
                'id': '2',
                'name': '产品展示',
                'description': '产品展示相关的素材',
                'color': '🟢 绿色',
                'status': '✅ 启用',
                'count': 298,
                'type': '主分类',
                'children': [
                    {'id': '2-1', 'name': '产品图片', 'count': 180, 'type': '子分类'},
                    {'id': '2-2', 'name': '产品视频', 'count': 118, 'type': '子分类'}
                ]
            },
            {
                'id': '3',
                'name': '模特试穿',
                'description': '模特试穿展示素材',
                'color': '🟡 黄色',
                'status': '✅ 启用',
                'count': 156,
                'type': '主分类',
                'children': []
            },
            {
                'id': '4',
                'name': '产品使用',
                'description': '产品使用场景素材',
                'color': '🔴 红色',
                'status': '⏸️ 禁用',
                'count': 89,
                'type': '主分类',
                'children': []
            },
            {
                'id': '5',
                'name': '背景音乐',
                'description': '视频背景音乐素材',
                'color': '🟣 紫色',
                'status': '✅ 启用',
                'count': 67,
                'type': '主分类',
                'children': [
                    {'id': '5-1', 'name': '轻音乐', 'count': 34, 'type': '子分类'},
                    {'id': '5-2', 'name': '电子音乐', 'count': 33, 'type': '子分类'}
                ]
            }
        ]

        self.categories = sample_categories
        self.update_category_tree()

        # 隐藏空状态，显示树形控件
        if self.categories:
            self.empty_category_frame.pack_forget()
        else:
            self.empty_category_frame.pack(expand=True)

    def update_category_tree(self):
        """更新分类树显示"""
        # 清空现有项目
        for item in self.category_tree.get_children():
            self.category_tree.delete(item)

        # 添加分类项目
        for category in self.categories:
            # 根据状态设置图标
            status_icon = "✅" if "启用" in category['status'] else "⏸️" if "禁用" in category['status'] else "🔒"

            # 插入主分类
            parent_item = self.category_tree.insert(
                '', 'end',
                text=f"{category['color'].split()[0]} {category['name']}",
                values=(category['count'], category['type'], status_icon),
                tags=('main_category',)
            )

            # 插入子分类
            for child in category.get('children', []):
                self.category_tree.insert(
                    parent_item, 'end',
                    text=f"  📁 {child['name']}",
                    values=(child['count'], child['type'], "✅"),
                    tags=('sub_category',)
                )

        # 配置标签样式
        self.category_tree.tag_configure('main_category', background=DesignSystem.COLORS['bg_primary'])
        self.category_tree.tag_configure('sub_category', background=DesignSystem.COLORS['gray_50'])

    # 事件处理方法
    def on_search_changed(self, event=None):
        """搜索条件改变"""
        search_text = self.search_var.get().lower()
        # TODO: 实现搜索过滤逻辑
        print(f"搜索: {search_text}")

    def on_category_selected(self, event):
        """分类选中事件"""
        selection = self.category_tree.selection()
        if selection:
            item = selection[0]
            category_text = self.category_tree.item(item, 'text')
            print(f"选中分类: {category_text}")
            self.show_category_details(item)

    def on_category_double_click(self, event):
        """分类双击事件"""
        selection = self.category_tree.selection()
        if selection:
            self.edit_category()

    def show_category_context_menu(self, event):
        """显示分类右键菜单"""
        item = self.category_tree.identify_row(event.y)
        if item:
            self.category_tree.selection_set(item)

            context_menu = tk.Menu(self.frame, tearoff=0)
            context_menu.add_command(label="✏️ 编辑分类", command=self.edit_category)
            context_menu.add_command(label="📁 添加子分类", command=self.add_subcategory)
            context_menu.add_separator()
            context_menu.add_command(label="📊 查看统计", command=self.view_category_stats)
            context_menu.add_command(label="📋 复制分类", command=self.copy_category)
            context_menu.add_separator()
            context_menu.add_command(label="🗑️ 删除分类", command=self.delete_category)

            context_menu.tk_popup(event.x_root, event.y_root)

    def show_category_details(self, item):
        """显示分类详情"""
        # 隐藏默认视图
        self.default_details_frame.pack_forget()

        # 显示详情信息
        category_text = self.category_tree.item(item, 'text')
        values = self.category_tree.item(item, 'values')

        # 创建详情显示
        if hasattr(self, 'current_details_frame'):
            self.current_details_frame.destroy()

        self.current_details_frame = ttk.Frame(self.details_container)
        self.current_details_frame.pack(fill="x")

        # 分类名称
        name_frame = ttk.Frame(self.current_details_frame)
        name_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))

        ttk.Label(name_frame, text="分类名称:", style='Heading.TLabel').pack(anchor="w")
        ttk.Label(name_frame, text=category_text.strip(), style='Body.TLabel').pack(anchor="w", pady=(DesignSystem.SPACING['xs'], 0))

        # 素材数量
        count_frame = ttk.Frame(self.current_details_frame)
        count_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))

        ttk.Label(count_frame, text="素材数量:", style='Heading.TLabel').pack(anchor="w")
        ttk.Label(count_frame, text=f"{values[0]} 个", style='Body.TLabel').pack(anchor="w", pady=(DesignSystem.SPACING['xs'], 0))

        # 分类类型
        type_frame = ttk.Frame(self.current_details_frame)
        type_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))

        ttk.Label(type_frame, text="分类类型:", style='Heading.TLabel').pack(anchor="w")
        ttk.Label(type_frame, text=values[1], style='Body.TLabel').pack(anchor="w", pady=(DesignSystem.SPACING['xs'], 0))

        # 状态
        status_frame = ttk.Frame(self.current_details_frame)
        status_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['lg']))

        ttk.Label(status_frame, text="状态:", style='Heading.TLabel').pack(anchor="w")
        ttk.Label(status_frame, text=values[2], style='Body.TLabel').pack(anchor="w", pady=(DesignSystem.SPACING['xs'], 0))

        # 操作按钮
        action_frame = ttk.Frame(self.current_details_frame)
        action_frame.pack(fill="x")

        edit_btn = create_primary_button(
            action_frame,
            text="✏️ 编辑",
            command=self.edit_category
        )
        edit_btn.pack(side="left", padx=(0, DesignSystem.SPACING['sm']))

        view_materials_btn = create_secondary_button(
            action_frame,
            text="📋 查看素材",
            command=self.view_category_materials
        )
        view_materials_btn.pack(side="left")

    # 操作方法
    def add_category(self):
        """添加新分类"""
        dialog = CategoryDialog(self.frame, "新建分类")
        if dialog.result:
            category_data = dialog.result
            messagebox.showinfo("成功", f"分类「{category_data['name']}」创建成功！")
            # TODO: 添加到数据并刷新树

    def add_subcategory(self):
        """添加子分类"""
        selection = self.category_tree.selection()
        if not selection:
            messagebox.showwarning("提示", "请先选择一个主分类")
            return

        dialog = CategoryDialog(self.frame, "新建子分类")
        if dialog.result:
            category_data = dialog.result
            messagebox.showinfo("成功", f"子分类「{category_data['name']}」创建成功！")

    def edit_category(self):
        """编辑分类"""
        selection = self.category_tree.selection()
        if not selection:
            messagebox.showwarning("提示", "请先选择要编辑的分类")
            return

        # 显示编辑表单
        if hasattr(self, 'current_details_frame'):
            self.current_details_frame.destroy()

        self.edit_frame.pack(fill="x")

        # 填充当前数据
        item = selection[0]
        category_text = self.category_tree.item(item, 'text')
        self.category_name_var.set(category_text.strip())

    def save_category(self):
        """保存分类"""
        name = self.category_name_var.get()
        if not name:
            messagebox.showwarning("提示", "请输入分类名称")
            return

        messagebox.showinfo("成功", f"分类「{name}」保存成功！")
        self.cancel_edit()

    def cancel_edit(self):
        """取消编辑"""
        self.edit_frame.pack_forget()
        self.default_details_frame.pack(fill="x")

    def delete_category(self):
        """删除分类"""
        selection = self.category_tree.selection()
        if not selection:
            messagebox.showwarning("提示", "请先选择要删除的分类")
            return

        item = selection[0]
        category_text = self.category_tree.item(item, 'text')

        if messagebox.askyesno("确认删除", f"确定要删除分类「{category_text.strip()}」吗？\n\n此操作不可撤销！"):
            self.category_tree.delete(item)
            messagebox.showinfo("成功", "分类删除成功！")

    def expand_all_categories(self):
        """展开所有分类"""
        def expand_item(item):
            self.category_tree.item(item, open=True)
            for child in self.category_tree.get_children(item):
                expand_item(child)

        for item in self.category_tree.get_children():
            expand_item(item)

    def collapse_all_categories(self):
        """折叠所有分类"""
        def collapse_item(item):
            self.category_tree.item(item, open=False)
            for child in self.category_tree.get_children(item):
                collapse_item(child)

        for item in self.category_tree.get_children():
            collapse_item(item)

    def import_categories(self):
        """导入分类"""
        messagebox.showinfo("提示", "导入分类功能开发中...")

    def export_categories(self):
        """导出分类"""
        messagebox.showinfo("提示", "导出分类功能开发中...")

    def view_category_stats(self):
        """查看分类统计"""
        messagebox.showinfo("提示", "分类统计功能开发中...")

    def copy_category(self):
        """复制分类"""
        messagebox.showinfo("提示", "复制分类功能开发中...")

    def view_category_materials(self):
        """查看分类下的素材"""
        messagebox.showinfo("提示", "即将跳转到素材列表页面...")
        self.app.show_page("material_list")


class CategoryDialog:
    """分类编辑对话框"""

    def __init__(self, parent, title="编辑分类"):
        self.result = None

        # 创建对话框窗口
        self.dialog = tk.Toplevel(parent)
        self.dialog.title(title)
        self.dialog.geometry("400x300")
        self.dialog.resizable(False, False)
        self.dialog.transient(parent)
        self.dialog.grab_set()

        # 居中显示
        self.dialog.update_idletasks()
        x = (self.dialog.winfo_screenwidth() // 2) - (400 // 2)
        y = (self.dialog.winfo_screenheight() // 2) - (300 // 2)
        self.dialog.geometry(f"400x300+{x}+{y}")

        self.create_dialog_content()

        # 等待对话框关闭
        self.dialog.wait_window()

    def create_dialog_content(self):
        """创建对话框内容"""
        main_frame = ttk.Frame(self.dialog, padding=DesignSystem.SPACING['xl'])
        main_frame.pack(fill="both", expand=True)

        # 分类名称
        ttk.Label(main_frame, text="分类名称:", style='Heading.TLabel').pack(anchor="w")
        self.name_var = tk.StringVar()
        name_entry = ttk.Entry(main_frame, textvariable=self.name_var, width=40)
        name_entry.pack(fill="x", pady=(DesignSystem.SPACING['xs'], DesignSystem.SPACING['md']))
        name_entry.focus()

        # 分类描述
        ttk.Label(main_frame, text="分类描述:", style='Heading.TLabel').pack(anchor="w")
        self.desc_var = tk.StringVar()
        desc_entry = ttk.Entry(main_frame, textvariable=self.desc_var, width=40)
        desc_entry.pack(fill="x", pady=(DesignSystem.SPACING['xs'], DesignSystem.SPACING['md']))

        # 分类颜色
        ttk.Label(main_frame, text="标签颜色:", style='Heading.TLabel').pack(anchor="w")
        self.color_var = tk.StringVar(value="🔵 蓝色")
        color_combo = ttk.Combobox(
            main_frame,
            textvariable=self.color_var,
            values=["🔵 蓝色", "🟢 绿色", "🟡 黄色", "🔴 红色", "🟣 紫色", "🟠 橙色"],
            state="readonly",
            width=37
        )
        color_combo.pack(fill="x", pady=(DesignSystem.SPACING['xs'], DesignSystem.SPACING['lg']))

        # 按钮区域
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill="x", side="bottom")

        cancel_btn = create_secondary_button(
            button_frame,
            text="取消",
            command=self.cancel
        )
        cancel_btn.pack(side="right", padx=(DesignSystem.SPACING['sm'], 0))

        ok_btn = create_primary_button(
            button_frame,
            text="确定",
            command=self.ok
        )
        ok_btn.pack(side="right")

        # 绑定回车键
        self.dialog.bind('<Return>', lambda e: self.ok())
        self.dialog.bind('<Escape>', lambda e: self.cancel())

    def ok(self):
        """确定按钮"""
        name = self.name_var.get().strip()
        if not name:
            messagebox.showwarning("提示", "请输入分类名称")
            return

        self.result = {
            'name': name,
            'description': self.desc_var.get().strip(),
            'color': self.color_var.get()
        }
        self.dialog.destroy()

    def cancel(self):
        """取消按钮"""
        self.dialog.destroy()
